package com.wswy.wzcx.ui.dmv

import android.content.Context
import com.che.libcommon.api.ApiOptionalResultObserver
import com.che.libcommon.api.BaseResult
import com.che.libcommon.api.page.PageList
import com.che.libcommon.api.page.Pagination
import com.che.libcommon.ui.VOMessage
import com.che.libcommon.utils.optional.Optional
import com.wswy.wzcx.AppContext
import com.wswy.wzcx.R
import com.wswy.wzcx.api.Api
import com.wswy.wzcx.model.AreaEntity
import com.wswy.wzcx.model.dmv.DepartmentInfo
import com.wswy.wzcx.model.dmv.ServiceInfoModel
import com.wswy.wzcx.module.LocManager
import io.reactivex.Single

internal class CarDepartmentPresenter(private val mView: ICarDepartmentView, private val context: Context) {

    private var serviceInfoModel: ServiceInfoModel? = null

    var pagination: Pagination<DepartmentInfo>? = null
        private set


    fun load(areaEntity: AreaEntity, serviceInfoModel: ServiceInfoModel?) {


        pagination?.release()

        this.serviceInfoModel = serviceInfoModel

        val api: (Int) -> Single<Optional<PageList<DepartmentInfo>>> = {


            val location = LocManager.getInstance().currentLocation

            val lat = location?.latitude?:0.0
            val lon = location?.longitude?:0.0

            Api.get().getDepartmentInfo(it, areaEntity.id, serviceInfoModel?.code,lat,lon).map {

                it.orNull()?.list?.apply {
                    val locManager = LocManager.getInstance()
                    val result = FloatArray(1)
                    forEach {
                        locManager?.distanceBetween(it.lat, it.lon, result)
                        it.distancKM = result[0] / 1000
                    }
                }
                it
            }
        }

        pagination = if (pagination == null) Pagination<DepartmentInfo>(api) else pagination?.setPaginationWrapper(api)

        pagination?.apply {


            setCallback(object : ApiOptionalResultObserver<List<DepartmentInfo>>() {


                override fun onApiResult(t: List<DepartmentInfo>?) {

                    t?.let {
                        mView.showResult(t, isFirst)
                    }
                    if (isEmpty) {
                        mView.showError(VOMessage.createEmpty(R.drawable.activity_default_empty, R.string.module_cgs, 0))
                    }

                }

                override fun onApiError(result: BaseResult<*>?) {
                    if (isFirst){
                        result?.let {
                            mView.showError(VOMessage.create(it.error))
                        }
                    }
                }
            })


        }

        pagination?.preLoad()

    }


    fun onDestroy() {

        pagination?.release()
    }

    companion object {


        private val TAG = "CarDepartmentPresenter"
    }


}
